package com.zhiwang.planet.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.zhiwang.planet.App
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerTaskComponent
import com.zhiwang.planet.event.AppUsageEvent
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.request.AppUsageTaskRequest
import com.zhiwang.planet.util.AppDetector
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.androidSchedule
import com.zhiwang.planet.util.responseVoidFunc
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit
import javax.inject.Inject


class AppUsageService : Service() {

    val TAG = "AppUsageService"

    companion object SOURL {

        var currTaskId = ""

        fun startDetectApp(context: Context, taskId: String, packageName: String, time: Int) {

            if (currTaskId == taskId)
                return Toaster.message("重复执行任务")

            val intent = Intent(context, AppUsageService::class.java)
            intent.apply {
                putExtra("Time", time)
                putExtra("PKG_NAME", packageName)
                putExtra("TASK_ID", taskId)
            }



            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else context.startService(intent)
        }
    }

    override fun onBind(intent: Intent?) = null

    var targetPackageName: String = ""

    var timePassed = 0

    var targetUsageTime = 0

    var disposable: Disposable? = null

    var targetFound = false

    var taskId: String = ""
    val notificationId = 112113

    @Inject
    lateinit var restApi: RestApi

    override fun onCreate() {
        super.onCreate()
        DaggerTaskComponent.builder()
                .appComponent((application as App).appComponent)
                .build()
                .inject(this)
        createNotification()
    }

    private lateinit var notification: Notification
    private lateinit var notificationManagerCompat: NotificationManagerCompat


    private fun createNotification() {
        notificationManagerCompat = NotificationManagerCompat.from(this)
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(BuildConfig.APPLICATION_ID, "星球任务服务", NotificationManager.IMPORTANCE_LOW)
            notificationChannel.enableLights(true)
            notificationChannel.setShowBadge(false)
            notificationManager.createNotificationChannel(notificationChannel)
            notification = NotificationCompat
                    .Builder(this, BuildConfig.APPLICATION_ID)
                    .setTicker("趣味星球")
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round))
                    .build()

            notificationManagerCompat.notify(notificationId, notification)
            startForeground(notificationId, notification)

        }
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        intent?.apply {
            val pkgName = intent.getStringExtra("PKG_NAME")
            val time = intent.getIntExtra("Time", 0)

            if (pkgName == targetPackageName) {
                Toaster.message("任务正在进行中")

            } else {
                taskId = intent.getStringExtra("TASK_ID")
                if (pkgName.isNotEmpty() && time > 0 && pkgName != targetPackageName) {
                    continuouslyDetect(pkgName, time)
                }
            }
        }

        return START_NOT_STICKY
    }

    private fun continuouslyDetect(pkgName: String, time: Int) {
        reset()
        targetUsageTime = time
        targetPackageName = pkgName
        disposable = Flowable.interval(2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({

                    if (BuildConfig.DEBUG)
                        Log.i(TAG, "continuouslyDetect: ----------tick---------------")

                    val found = AppDetector.queryAppUsage(this, pkgName)

                    if (targetFound && found && BuildConfig.DEBUG) {
                        timePassed += 2
                        Log.i(TAG, "continuouslyDetect: $timePassed ${targetUsageTime}")
                    }

                    if (targetFound && found.not()) {
                        //提示继续玩
                    }

                    if (timePassed > targetUsageTime) {
                        postTaskAndExit()
                    }

                    if (targetFound.not() && found && BuildConfig.DEBUG) {
                        Log.i(TAG, "continuouslyDetect: ----目标 app 正在使用--")
                    }

                    targetFound = found

                }, {

                }, {

                })
    }

    private fun postTaskAndExit() {

        with(restApi) {
            postAppUsageTask(AppUsageTaskRequest(taskId = taskId))
                    .androidSchedule()
                    .responseVoidFunc()
                    .subscribe({

                    }, {
                        stopSelf()

                    }, {
                        //onComplete
                        Toaster.message(getString(R.string.task_verifying))
                        AppUsageEvent.taskId = taskId
                        EventBus.getDefault().post(AppUsageEvent)
                    })
        }
    }


    fun reset() {
        disposable?.dispose()
        targetFound = false
        timePassed = 0
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable?.dispose()
    }

}